package com.hznu.coursemanagerbackend.modules.sys.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.api.client.util.Value;
import com.hznu.coursemanagerbackend.common.utils.FileUtils;
import com.hznu.coursemanagerbackend.common.utils.PageUtils;
import com.hznu.coursemanagerbackend.common.validator.Assert;
import com.hznu.coursemanagerbackend.modules.sys.bean.UserLoadBase;
import com.hznu.coursemanagerbackend.modules.sys.bean.UserLoadDto;
import com.hznu.coursemanagerbackend.modules.sys.entity.StudentInfo;
import com.hznu.coursemanagerbackend.modules.sys.entity.TeacherInfo;
import com.hznu.coursemanagerbackend.modules.sys.entity.User;
import com.hznu.coursemanagerbackend.modules.sys.service.StudentInfoService;
import com.hznu.coursemanagerbackend.modules.sys.service.TeacherInfoService;
import com.hznu.coursemanagerbackend.modules.sys.service.UserService;
import com.hznu.coursemanagerbackend.myBeans.R;
import com.xuxueli.poi.excel.ExcelImportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DragonDoor
 * @since 2018-11-12
 */
@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping("/user")
@Api(description = "用户管理接口",value = "user")
public class UserController extends AbstractController {

    @Autowired
    private UserService userService;

    @Autowired
    private TeacherInfoService teacherInfoService;

    @Autowired
    private StudentInfoService studentInfoService;

    @Value("${template.userTemplatepath}")
    private String userTemplatepath = "用户导入模板.xls";

    @ApiOperation("添加用户")
    @PostMapping("/add")
    public R addUser(@RequestBody User user) throws Exception{
        try{
            userService.add(user);
            user.setWorkid(user.getUsername());
            user.setSchoolid(user.getSchoolid());
            user.setUniversityid(user.getUniversityid());
            if(user.getUsertype()==1){
                TeacherInfo teacherInfo = user.getTeacherInfo();
                teacherInfo.setUserid(user.getId());
                teacherInfoService.insert(teacherInfo);
            }else if(user.getUsertype()==2)
            {
                StudentInfo studentInfo = user.getStudentInfo();
                studentInfo.setUserid(user.getId());
                studentInfoService.insert(studentInfo);
            }
            return R.ok("添加成功");
        }catch(Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }

    /**
     * 获取登录的用户信息
     */
    @ApiOperation(value = "获取登录的用户信息")
    @GetMapping("/info")
    public R info() {
        User user = getUser();
        user.setSalt(null);
        user.setPassword(null);
        if(user.getUsertype()==1)
        {
            user.setTeacherInfo(teacherInfoService.selectOne(new EntityWrapper<TeacherInfo>().eq("userid",user.getId())));
        }else if(user.getUsertype()==2)
        {
            user.setStudentInfo(studentInfoService.selectOne(new EntityWrapper<StudentInfo>().eq("userid",user.getId())));
        }
        return R.ok().put("user", getUser());
    }

    @ApiOperation("通过id查找用户")
    @GetMapping("/find/{id}")
    public R findUserById(@PathVariable Integer id){
        return R.ok().put("user",userService.findById(id));
    }

    /**
     * @author: DragonDoor
     * @Date: 2018/12/2 13:16
     * @Description:
     */
    @ApiOperation(value = "条件查询用户分页")
    @PostMapping("/list")
    public R list(@RequestParam Map<String,Object> params)
    {
        PageUtils page = userService.queryPage(params);
        return R.ok().put("page",page);
    }

    /**
     * @author: DragonDoor
     * @Date: 2018/12/2 13:34
     * @Description:
     */
    @ApiOperation(value = "用户信息修改")
    @PostMapping("/modify")
    public R modify(@RequestBody User user)
    {
        userService.modify(user);
        return R.ok("用户信息修改成功");
    }

    /**
     * @Description:用户修改密码
     * @param:
     * @return:
     * @author: TateBrown
     * @Date: 2018/12/4
     */
     @ApiOperation("用户修改密码")
     @PostMapping("/modifyPwd")
     public R modifyPwd(@RequestBody User user){
         User oldUser = userService.selectById(user.getId());
         if(!userService.validatePassword(oldUser,user.getPassword())){
             return R.error(HttpStatus.SC_METHOD_FAILURE,"原密码不正确");
         }else{
             if(!user.getNewPassword().equals(user.getCheckPassword())){
                 return R.error(HttpStatus.SC_CONFLICT,"新密码与确认密码不同");
             }else{
                 user.setPassword(user.getNewPassword());
                 userService.modify(user);
                 return R.ok("密码修改成功");
             }
         }
     }

    /**
     * @Description:批量导入用户模板
     * @param:
     * @return:
     * @author: TateBrown
     * @Date: 2018/12/24
     */
    @ApiOperation("下载批量导入用户的模板")
    @GetMapping("/downloadtemplate")
    public ResponseEntity<byte[]> downloadTemplate(HttpServletRequest request){
        try{
            byte[] data= FileUtils.ConvertFiletoByte(userTemplatepath);
            HttpHeaders headers=new HttpHeaders();
            String filename=new String("用户导入模板.xls".getBytes("UTF-8"),"iso-8859-1");
            headers.setContentDispositionFormData("attachment",filename);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            org.springframework.http.HttpStatus statusCode= org.springframework.http.HttpStatus.OK;
            return new ResponseEntity<byte[]>(data,headers,statusCode);
        }catch(Exception e){
            logger.error(e.toString());
            return null;
        }
    }

    /**
     * @Description: 批量导入用户
     * @param: userType,file
     * @return:
     * @author: TateBrown
     * @Date: 2018/12/24
     */
     @ApiOperation("批量导入用户")
     @PostMapping("/LoadUser")
    public R LoadUser(UserLoadBase userLoadBase, @RequestParam("file")MultipartFile file){
         try{
             Assert.isNull(file,"文件不能为空");
             Assert.isNull(userLoadBase.getUniversityid(),"大学未选择");
             Assert.isNull(userLoadBase.getSchoolid(),"学院未选择");
             String Suffix=FileUtils.getSuffix(file.getOriginalFilename());
             if(!Suffix.equals(".xls")){
                 return R.error("上传失败，请检查文件后缀，仅支持xls格式的Excel");
             }
             List<Object> userDtoList= ExcelImportUtil.importExcel(UserLoadDto.class,file.getInputStream());
             Assert.isNull(userDtoList,"导入用户为空");
             Integer count=userService.LoadBatch(userDtoList,userLoadBase);
             return R.ok("添加成功，共添加了"+count+"个用户");
         }catch(Exception e){
         logger.error(e.toString());
         return R.error(e.getMessage());
         }
     }
}

